package com.ashin;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.sound.midi.Soundbank;
import java.util.concurrent.*;

/**
 * @author Ashin
 */
public class TestRedisnx {

    public static final String TESTSETNX = "testsetnx";

    @Test
    public void testSetnx() throws InterruptedException {

        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(1000);
        poolConfig.setMaxIdle(32);
        poolConfig.setMaxWaitMillis(100 * 1000);
        poolConfig.setTestOnBorrow(false);
        poolConfig.setTestOnCreate(false);

        JedisPool jedisPool = new JedisPool(poolConfig, "localhost", 6379);

        CyclicBarrier cb = new CyclicBarrier(50, () -> System.out.println("同时执行"));
        ExecutorService executorService = Executors.newFixedThreadPool(50);
        for (int i = 0; i < 50; i++) {
            System.out.print(i);
            executorService.execute(() -> {
                try {
                    cb.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Jedis jedis = jedisPool.getResource();
                Long setnx = jedisPool.getResource().setnx(TESTSETNX, "100");
                if (setnx == 0) {
                    System.out.println(jedis.get(TESTSETNX) + "   12");
                    System.out.println(jedis.decr(TESTSETNX));

                } else {
                    System.out.println("我是第一个" + Thread.currentThread().getName());
                    System.out.println(jedis.get(TESTSETNX));
                    jedis.decr(TESTSETNX);
                }

                jedis.close();

            });
        }

        TimeUnit.SECONDS.sleep(10);


    }
}
